#include "signal_handler.h"
#include "Timer.h"
#include <windows.h>

bool SignalHandler::shutdownRequested = false;

void SignalHandler::setupSignalHandlers() {
    // ���ÿ���̨�¼���������Windows���У�
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)SignalHandler::handleShutdownSignal, TRUE);

    // ���ñ�׼�źŴ�����
    signal(SIGINT, signalHandler);   // Ctrl+C
    signal(SIGTERM, signalHandler);  // ��ֹ�ź�
    signal(SIGABRT, signalHandler);  // �쳣��ֹ

    std::cout << Timer::getCurTime() << ": �źŴ����������ã�֧�����Źر�" << std::endl;
}

void SignalHandler::signalHandler(int signal) {
    std::cout << "\n" << Timer::getCurTime() << ": ���յ��ź� " << signal << "����ʼ���Źر�..." << std::endl;
    gracefulShutdown();
}

void SignalHandler::gracefulShutdown() {
    if (shutdownRequested) {
        std::cout << Timer::getCurTime() << ": ǿ���˳�����" << std::endl;
        exit(1);
    }

    shutdownRequested = true;
    std::cout << Timer::getCurTime() << ": ���ڱ������ݲ��رշ�����..." << std::endl;

    // ����DB��terminate����ȷ�����ݳ־û�
    DB* db = DB::getInstance();
    if (db) {
        db->terminate();
        DB::release();
    }

    std::cout << Timer::getCurTime() << ": �������Ѱ�ȫ�ر�" << std::endl;
    std::cout.flush(); // ȷ����Ϣ�������
    exit(0);
}

// Windows����̨�¼�������
BOOL WINAPI SignalHandler::handleShutdownSignal(DWORD dwCtrlType) {
    switch (dwCtrlType) {
    case CTRL_C_EVENT:
    case CTRL_CLOSE_EVENT:
    case CTRL_BREAK_EVENT:
    case CTRL_LOGOFF_EVENT:
    case CTRL_SHUTDOWN_EVENT:
        std::cout << "\n" << Timer::getCurTime() << ": ��⵽ϵͳ�ر��¼�����ʼ���Źر�..." << std::endl;
        SignalHandler::gracefulShutdown();
        return TRUE;
    default:
        return FALSE;
    }
}

// 全局函数实现
void setupGracefulShutdown() {
    SignalHandler::setupSignalHandlers();
}